<?php
/**
 * 公共方法
 * @author lzy
 */
/**
 * url 转化
 */
if (!function_exists('url')) {
    /**
     * Url生成
     * @param string $url 路由地址
     * @param string|array $vars 变量
     * @param bool|string $suffix 生成的URL后缀
     * @param bool|string $domain 域名
     * @return string
     */
    function url($url = '', $vars = '', $suffix = true, $domain = false)
    {
        return App\Common\Library\Url::build($url, $vars, $suffix, $domain);
    }
}

/**
 * 密码加密
 * @return int
 * @author   <278805354@qq.com>
 */
function lzy_ucenter_md5($str, $key = 'lzyUCenter')
{
    return '' === $str ? '' : md5(sha1($str) . $key);
}

/**
 * 记录行为日志，并执行该行为的规则
 * @param string $action 行为标识
 * @param string $model 触发行为的模型名
 * @param int $record_id 触发行为的记录id
 * @param int $user_id 执行行为的用户id
 * @return boolean
 * @author lzy
 */
function action_log($action = null, $model = null, $record_id = null, $user_id = null)
{
    //参数检查
    if (empty($action) || empty($model) || empty($record_id)) {
        return '参数不能为空';
    }
    if (empty($user_id)) {
        $user_id = !empty(UID) ? 0 : UID;
    }

    $actionModel = new \App\Model\Action();
    $actionInfo = $actionModel->findOne(['name'=>$action]);
    if (empty($actionInfo)) {
        return "查无此记录类型";
    }
    if ($actionInfo['status'] != 1) {
        return '该行为被禁用或删除';
    }

    $now_time = time();
    //插入行为日志
    $data['action_id'] = $actionInfo['id'];
    $data['user_id'] = $user_id;
    $data['action_ip'] = ip2long(getClientIp());
    $data['model'] = $model;
    $data['record_id'] = $record_id;
    $data['create_time'] = $now_time;

    //解析日志规则,生成日志备注
    if (!empty($actionInfo['log'])) {
        if (preg_match_all('/\[(\S+?)\]/', $actionInfo['log'], $match)) {
            $log['user'] = $user_id;
            $log['record'] = $record_id;
            $log['model'] = $model;
            $log['time'] = $now_time;
            $log['data'] = array('user' => $user_id, 'model' => $model, 'record' => $record_id, 'time' => $now_time);
            foreach ($match[1] as $value) {
                $param = explode('|', $value);
                if (isset($param[1])) {
                    $replace[] = call_user_func($param[1], $log[$param[0]]);
                } else {
                    $replace[] = $log[$param[0]];
                }
            }
            $data['remark'] = str_replace($match[0], $replace, $actionInfo['log']);
        } else {
            $data['remark'] = $actionInfo['log'];
        }
    } else {
        //未定义日志规则，记录操作url
        $data['remark'] = '操作url：' . $_SERVER['REQUEST_URI'];
    }
    $actionLogModel = new\App\Model\ActionLog();
    $actionLogModel->addData($data);
    if (!empty($actionInfo['rule'])) {   //规则操作-----执行行为---放到队列中执行(队列)
        $param = array();
        $param['user'] = $user_id;    //操作者
        $param['record'] = $record_id;   //记录id
        $param['model'] = $model;     //模型
        $param['action_id'] = $actionInfo['id'];  //操作的id

        // $res = $iAction->executeAction($actionInfo->rule,$param);
    }
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function getClientIp($type = 0, $adv = false)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL)
        return $ip[$type];
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos)
                unset($arr[$pos]);
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 时间戳格式化
 * @param int $time
 * @return string 完整的时间显示
 * @author huajie <banhuajie@163.com>
 */
function time_format($time = NULL, $format = 'Y-m-d H:i')
{
    $time = $time === NULL ? NOW_TIME : intval($time);
    return date($format, $time);
}

/**
 * 获取昵称
 * @param $uid
 * @return array|null
 * @throws Throwable
 * @throws \EasySwoole\Mysqli\Exceptions\ConnectFail
 * @throws \EasySwoole\Mysqli\Exceptions\PrepareQueryFail
 */
function get_nickname($uid)
{
    $memberModel = new\App\Model\Member();
    return $memberModel->getFiledValue(['uid', $uid, '='], 'nickname');
}

/**
 * 数据签名认证
 * @param array $data 被认证的数据
 * @return string       签名
 * @author   <278805354@qq.com>
 */
function data_auth_sign($data)
{
//数据类型检测
    if (!is_array($data)) {
        $data = (array)$data;
    }
    ksort($data); //排序
    $code = http_build_query($data); //url编码并生成query字符串
    $sign = sha1($code); //生成签名
    return $sign;
}

/**
 * 返回登陆后用户uid
 * @return int
 * @author   <278805354@qq.com>
 */
function is_login($token)
{
    if (empty($token)) {
        return 0;
    } else {
        $userArr=json_decode(base64_decode($token),true);
        //解析出uid
        if(empty($userArr['uid'])){
            return 0;
        }
        return $userArr['uid'];
    }
}

/**
 * 判断是否是超级管理员
 * @return boolean
 * @author   <278805354@qq.com>
 */
function is_administrator($uid = null)
{
    $uid = is_null($uid) ? is_login() : $uid;
    $conf = \EasySwoole\EasySwoole\Config::getInstance()->getConf('AUTH_CONFIG');
    //判断
    return $uid && (intval($uid) === $conf['IS_ADMINISTATOR']);
}

// 不区分大小写的in_array实现
function in_array_case($value, $array)
{
    return in_array(strtolower($value), array_map('strtolower', $array));
}

/**
 * 树组装
 * @author   <278805354@qq.com>
 * @param type $list
 * @param type $pk
 * @param type $pid
 * @param type $child
 * @param type $root
 * @return type
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0) {
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = & $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] = & $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = & $refer[$parentId];
                    $parent[$child][] = & $list[$key];
                }
            }
        }
    }
    return $tree;
}